package com.carleasoft.mps.core.utils;
import cn.hutool.core.collection.CollectionUtil;
import com.carleasoft.mps.core.tree.Tree;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author taoyujing
 * @date 2021-07-16 14:15
 * @project service
 */
public class TreeUtil {
    private volatile static TreeUtil INSTANCE;
    private final String parentCode = "0";
    // 构造方法私有化
    private TreeUtil() {

    }

    // 获取树工具单例 （DCL单例）
    public static TreeUtil getInstance() {
        if (INSTANCE == null) {
            synchronized (TreeUtil.class) {
                if (INSTANCE == null) {
                    INSTANCE = new TreeUtil();
                }
            }
        }
        return INSTANCE;
    }

    public List<Tree> enquireTree(List<Tree> trees) {

        if (trees.isEmpty()) {
            return null;
        }

        // 过滤空对象
         trees = trees.stream().filter(Tree -> Tree != null).collect(Collectors.toList());
        List<Tree> list = new LinkedList<>();
        for (Tree tree : trees) {
            if (parentCode.equals(tree.getParentCode())) {
                List<Tree> childrenNode = getChildrenNode(tree.getCode(), trees, tree.getChildren());
                if (childrenNode != null && childrenNode.size() >0) tree.setChildren(childrenNode);
                list.add(tree);
            }
        }

        return list;

    }

    private List<Tree> getChildrenNode(String categoryCode, List<Tree> categoryNameTreeVos, List<Tree> list2) {
        for (Tree department : categoryNameTreeVos) {
            if (categoryCode.equals(department.getParentCode())){
                if (CollectionUtil.isEmpty(list2)){
                    list2 = new ArrayList<>();
                }
                // 递归获取子节点下的子节点，即设置树控件中的children
                list2.add(department);
                department.setChildren(getChildrenNode(department.getCode(), categoryNameTreeVos, department.getChildren()));
            }
        }
        return list2;
    }
}
